<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title>邮箱配置管理</title>
	<link rel="stylesheet" href="../../component/pear/css/pear.css" />
</head>

<body class="pear-container">
	<!-- 筛选表单区域 -->
	<div class="layui-card">
		<div class="layui-card-body">
			<form class="layui-form" action="">
				<div class="layui-form-item">
					<div class="layui-form-item layui-inline">
						<label class="layui-form-label">配置名称</label>
						<div class="layui-input-inline">
							<input type="text" name="name" id="name" placeholder="输入配置名称" class="layui-input">
						</div>
					</div>
					<div class="layui-form-item layui-inline">
						<label class="layui-form-label">SMTP</label>
						<div class="layui-input-inline">
							<input type="text" name="email_host" id="email_host" placeholder="输入SMTP服务器" class="layui-input">
						</div>
					</div>
					<div class="layui-form-item layui-inline">
						<label class="layui-form-label">是否默认</label>
						<div class="layui-input-inline">
							<select name="is_default" id="is_default" lay-search>
								<option value="">请下拉选择</option>
								<option value="true">是</option>
								<option value="false">否</option>
							</select>
						</div>
					</div>
					<div class="layui-form-item layui-inline">
						<label class="layui-form-label">配置状态</label>
						<div class="layui-input-inline">
							<select name="is_active" id="is_active" lay-search>
								<option value="">请下拉选择</option>
								<option value="1">开启</option>
								<option value="0">关闭</option>
							</select>
						</div>
					</div>
					<br>
					<div class="layui-form-item layui-inline">
						<button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="email-query">
							<i class="layui-icon layui-icon-search"></i>
							查询
						</button>
						<button type="reset" class="pear-btn pear-btn-md">
							<i class="layui-icon layui-icon-refresh"></i>
							重置
						</button>
					</div>
				</div>
			</form>
		</div>
	</div>

	<!-- 表格展示区域 -->
	<div class="layui-card">
		<div class="layui-card-body">
			<table id="base-table" lay-filter="base-table"></table>
		</div>
	</div>

	<!-- 表格工具栏（新增按钮） -->
	<script type="text/html" id="base-toolbar">
		<button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add">
	        <i class="layui-icon layui-icon-add-1"></i>
	        新增
	    </button>
	</script>

	<!-- 表格操作列（编辑/删除按钮） -->
	<script type="text/html" id="base-bar">
		<button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="edit">
			<i class="layui-icon layui-icon-edit"></i>编辑
		</button>
		<button class="pear-btn pear-btn-danger pear-btn-sm" lay-event="remove">
			<i class="layui-icon layui-icon-delete"></i>删除
		</button>
	</script>

	<!-- 时间格式化模板 -->
	<script type="text/html" id="base-createTime">
		{{layui.util.toDateString(d.create_time, 'yyyy-MM-dd HH:mm:ss')}}
	</script>
	<script type="text/html" id="base-updateTime">
		{{layui.util.toDateString(d.update_time, 'yyyy-MM-dd HH:mm:ss')}}
	</script>

	<!-- 是否默认配置格式化 -->
	<script type="text/html" id="base-isDefault">
		{{#if (d.is_default) { }}
			<i class="layui-icon layui-icon-ok" style="font-size: 20px; color: #52c41a;"><span>是</span></i>  
		{{# }else{ }}
			<i class="layui-icon layui-icon-close" style="font-size: 20px; color: #ff4d4f;"><span>否</span></i> 
		{{# } }}
	</script>

	<!-- 配置状态格式化 -->
	<script type="text/html" id="base-isActive">
		{{#if (d.is_active == 1) { }}
			<i class="layui-icon layui-icon-face-smile" style="font-size: 20px; color: #1E9FFF;"><span>开启</span></i>  
		{{# }else if(d.is_active == 0){ }}
			<i class="layui-icon layui-icon-face-cry" style="font-size: 20px; color: #ff1e1e;"><span>关闭</span></i> 
		{{# } }}
	</script>

	<!-- 引入依赖JS -->
	<script src="../../component/com/api.js"></script>
	<script src="../../component/com/auth.js"></script>
	<script src="../../component/layui/layui.js"></script>
	<script src="../../component/pear/pear.js"></script>
	<script>
		layui.use(['table', 'form', 'jquery', 'common'], function () {
			let table = layui.table;
			let form = layui.form;
			let $ = layui.jquery;
			let common = layui.common;
			// 模块路径（对应新增/编辑页面的路径）
			let MODULE_PATH = "config/";
			// 后端接口基础地址 + Token（复用账户页面逻辑）
			let API_BASE_URL = apiConfig.baseUrl;
			let token = window.localStorage.getItem("token") || window.sessionStorage.getItem("token")

			// 表格列定义（匹配EmailConfig模型字段）
			let cols = [
				[{
					type: 'checkbox'
				},
				{
					title: '序号',
					field: 'id',
					align: 'left',
					width: 80,
				},
				{
					title: '配置名称',
					field: 'name',
					align: 'left',
					width: 100,
				},
				{
					title: 'SMTP服务器',
					field: 'email_host',
					align: 'left',
					width: 130,
				},
				{
					title: 'SMTP端口',
					field: 'email_port',
					align: 'center',
					width: 120,
				},
				{
					title: '邮箱账号',
					field: 'email_user',
					align: 'left',
					width: 200,
				},
				{
					title: '邮箱授权码',
					field: 'email_password',
					align: 'left',
					width: 200,
				},
				{
					title: '是否SSL',
					field: 'use_ssl',
					align: 'center',
					width: 120,
					templet: function(d) {
						return d.use_ssl ? '<span style="color: #52c41a;">是</span>' : '<span style="color: #ff4d4f;">否</span>';
					}
				},
				{
					title: '是否默认',
					field: 'is_default',
					align: 'center',
					width: 120,
					templet: '#base-isDefault'
				},
				{
					title: '配置状态',
					field: 'is_active',
					align: 'center',
					width: 120,
					templet: '#base-isActive'
				},
				{
					title: '创建时间',
					field: 'create_time',
					align: 'center',
					width: 180,
					templet: '#base-createTime',
				},
				{
					title: '更新时间',
					field: 'update_time',
					align: 'center',
					width: 180,
					templet: '#base-updateTime',
					hide: true
				},
				{
					title: '操作',
					toolbar: '#base-bar',
					align: 'center',
					width: 180,
					fixed: "right"
				}
				]
			]

			// 渲染表格（复用账户页面分页、请求头、数据解析逻辑）
			table.render({
				elem: '#base-table',
				// 邮箱配置后端接口地址（对应之前写的EmailConfigListCreateView）
				url: `${API_BASE_URL}/email/config/`,
				page: true,
				// 分页参数配置（与后端保持一致）
				request: {
					pageName: 'page',
					limitName: 'limit'
				},
				// 分页条数选择器
				limits: [10, 20, 30, 40, 50, 100],
				limit: 10,
				cols: cols,
				skin: 'line',
				toolbar: '#base-toolbar',
				// 请求头携带Token（权限验证）
				headers: {
					"Authorization": token
				},
				// 解析后端返回数据（与账户接口返回格式一致）
				parseData: function (res) {
					return {
						"code": res.success ? 0 : 1,
						"msg": res.message || "操作成功",
						"count": res.data.count,
						"data": res.data.results,
						"curr": res.data.current_page
					};
				},
				// 默认工具栏（刷新、导出等）
				defaultToolbar: [{
					title: '刷新',
					layEvent: 'refresh',
					icon: 'layui-icon-refresh',
				}, 'filter', 'print', 'exports']
			});

			// 表格行操作事件（编辑/删除）
			table.on('tool(base-table)', function (obj) {
				switch (obj.event) {
					case "edit":
						window.edit(obj)  
						break;
					case "remove":
						window.remove(obj)
						break;
				}
			});

			// 表格工具栏事件（新增/刷新）
			table.on('toolbar(base-table)', function (obj) {
				switch (obj.event) {
					case "add":
						window.add(obj)
						break;
					case "refresh":
						window.refresh(obj)
						break;
				}
			});

			// 筛选表单提交事件
			form.on('submit(email-query)', function (data) {
				table.reload('base-table', {
					where: data.field // 携带筛选参数刷新表格
				})
				return false;
			});

			// 新增配置：打开新增弹窗
			window.add = function () {
				layer.open({
					type: 2,
					title: '新增邮箱配置',
					shade: 0.1,
					// 适配移动端和PC端
					area: [common.isModile() ? '100%' : '650px', common.isModile() ? '100%' : '500px'],
					content: MODULE_PATH + 'email-config-add.html'
				});
			}

			// 编辑配置：携带ID打开编辑弹窗
			window.edit = function (obj) {
				layer.open({
					type: 2,
					title: `编辑邮箱配置: [${obj.data.name}]`,
					shade: 0.1,
					area: [common.isModile() ? '100%' : '650px', common.isModile() ? '100%' : '500px'],
					content: MODULE_PATH + `email-config-edit.html?id=${obj.data.id}`
				});
			}

			// 删除配置：调用后端删除接口（逻辑删除）
			window.remove = function (obj) {
				layer.confirm(`确定要删除配置：[ ${obj.data.name} ] ？`, {
					icon: 3,
					title: '提示: 配置删除'
				}, function (index) {
					layer.close(index);
					let loading = layer.load();
					$.ajax({
						// 对应EmailConfigRetrieveUpdateDestroyView的删除接口
						url: `${API_BASE_URL}/email/config/${obj.data.id}/`,
						dataType: 'json',
						type: 'delete',
						headers: {
							"Authorization": token
						},
						success: function (result) {
							layer.close(loading);
							if (result.success) {
								layer.msg(result.message, {
									icon: 1,
									time: 1000
								}, function () {
									obj.del(); // 删除表格行
								});
							} else {
								layer.msg(result.message, {
									icon: 2,
									time: 1000
								});
							}
						}
					})
				});
			}

			// 刷新表格
			window.refresh = function (param) {
				table.reload('base-table');
			}
		})
	</script>
</body>

</html>